﻿using BySoft.Server.Business;
using BySoft.Server.Business.UserCode;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.StockManage
{
    public partial class MatReturnEdit : AuthBasePage
    {
        #region 属性定义
        private DataTable DtMatReturnData
        {
            get
            {
                if (null == Session["DtMatReturnData"])
                {
                    return CreateDT();
                }
                else
                {
                    return (DataTable)Session["DtMatReturnData"];
                }
            }
            set
            {
                Session["DtMatReturnData"] = value;
            }
        }

        private DataTable CreateDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("BillDetailID");//0
            dt.Columns.Add("MatInStockDetailID");//1 
            dt.Columns.Add("MatInStockID");//2 
            dt.Columns.Add("WorkOrderNo");//4
            dt.Columns.Add("MaterialID");//5
            dt.Columns.Add("MaterialName");//6
            dt.Columns.Add("Specifications");//7
            dt.Columns.Add("Unit");//8
            dt.Columns.Add("InStockNum");//9
            dt.Columns.Add("LeftNums");//10
            dt.Columns.Add("Nums");//11
            dt.Columns.Add("MMNumber");//13
            dt.Columns.Add("SingleMMNumber");//13
            dt.Columns.Add("IsNew");//14 
            dt.Columns.Add("IsDel");//14
            return dt;
        }
        #endregion

        #region 初始化及绑定控件
        private void InitData()
        {
            SetControlAttr(new BsPurchaseEntity(), tBase);

            string id = HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id"));
            if (!string.IsNullOrEmpty(id))
            {
                DataTable dt = BsMatReturnBusiness.GetDataByID(id);
                this.lblBillID.Text = id;
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataRow row1 = dt.Rows[0];
                    this.cpBillDate.Value = string.Format("{0:yyyy-MM-dd}",row1["BillDate"]);
                    this.ddlReturnReason.SelectedValue = CommonMethod.GetString(row1["ReturnReason"]);
                    DataTable dtemp = DtMatReturnData.Copy();
                    foreach(DataRow dr in dt.Rows)
                    {
                        DataRow drow = dtemp.NewRow();
                        drow["BillDetailID"]=CommonMethod.GetString(dr["BillDetailID"]);//0
                        drow["MatInStockDetailID"] = CommonMethod.GetString(dr["MatInStockDetailID"]);//1 
                        drow["MatInStockID"] = CommonMethod.GetString(dr["MatInStockID"]);//2 
                        drow["WorkOrderNo"] = CommonMethod.GetString(dr["WorkOrderNo"]);//4
                        drow["MaterialID"] = CommonMethod.GetString(dr["MaterialID"]);//5
                        drow["MaterialName"] = CommonMethod.GetString(dr["MaterialName"]);//6
                        drow["Specifications"] = CommonMethod.GetString(dr["Specifications"]);//7
                        drow["Unit"] = CommonMethod.GetString(dr["Unit"]);//8
                        drow["InStockNum"] = CommonMethod.GetString(dr["InStockNum"]);//9
                        drow["LeftNums"] = CommonMethod.GetString(dr["LeftNums"]);//10
                        drow["Nums"] = CommonMethod.GetString(dr["Nums"]);//11
                        drow["MMNumber"] = CommonMethod.GetString(dr["MMNumber"]);//13
                        drow["SingleMMNumber"] = CommonMethod.GetString(dr["SingleMMNumber"]);//13
                        drow["IsNew"]="-1";//14 
                        drow["IsDel"]="-1";//14
                        dtemp.Rows.Add(drow);
                    }
                    dtemp.AcceptChanges();
                    DtMatReturnData = dtemp.Copy();
                }
            }
            BindData();
        }
        #endregion

        #region 控件事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DtMatReturnData = null;
                BindDDL();
                grdResult.Style.Add("word-break", "keep-all");
                grdResult.Style.Add("word-wrap", "normal");
                InitData();
            }
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();");
        }

        private void BindDDL()
        {
            BindParameterForListControl("ReturnReason", ddlReturnReason);
            UIHelper.InsertFirstItem(ddlReturnReason);
        }
        private void AddPro()
        {
            DtMatReturnData = GetAddPro(DtMatReturnData).Copy();
        }
        private DataTable GetAddPro(DataTable dt)
        {
            DataTable dtTemp = dt.Copy();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                Label lblBillDetailID = gvr.FindControl("lblBillDetailID") as Label;
                Label lblMatInStockDetailID = gvr.FindControl("lblMatInStockDetailID") as Label;
                Label lblMatInStockID = gvr.FindControl("lblMatInStockID") as Label;
                Label lblWorkOrderNo = gvr.FindControl("lblWorkOrderNo") as Label;
                Label lblMaterialID = gvr.FindControl("lblMaterialID") as Label;
                Label lblMaterialName = gvr.FindControl("lblMaterialName") as Label;
                Label lblSpecifications = gvr.FindControl("lblSpecifications") as Label;
                Label lblUnit = gvr.FindControl("lblUnit") as Label;
                Label lblInStockNum = gvr.FindControl("lblInStockNum") as Label;
                Label lblLeftNums = gvr.FindControl("lblLeftNums") as Label;
                TextBox txtNums = gvr.FindControl("txtNums") as TextBox;
                Label lblSingleMMNumber = gvr.FindControl("lblSingleMMNumber") as Label;
                TextBox txtMMNumber = gvr.FindControl("txtMMNumber") as TextBox;

                string MaterialID = CommonMethod.GetString(lblMaterialID.Text);


                DataRow[] drs = dtTemp.Select("MaterialID='" + MaterialID + "'");
                if (drs.Length > 0)
                {

                    drs[0]["BillDetailID"] = GetGridViewString(lblBillDetailID);
                    drs[0]["MatInStockDetailID"] = GetGridViewString(lblMatInStockDetailID);
                    drs[0]["MatInStockID"] = GetGridViewString(lblMatInStockID);
                    drs[0]["WorkOrderNo"] = GetGridViewString(lblWorkOrderNo);
                    drs[0]["MaterialID"] = GetGridViewString(lblMaterialID);
                    drs[0]["MaterialName"] = GetGridViewString(lblMaterialName);
                    drs[0]["Specifications"] = GetGridViewString(lblSpecifications);
                    drs[0]["Unit"] = GetGridViewString(lblUnit);
                    drs[0]["InStockNum"] = GetGridViewString(lblInStockNum);
                    drs[0]["Nums"] = GetGridViewString(txtNums);
                    drs[0]["LeftNums"] = GetGridViewString(lblLeftNums);
                    drs[0]["SingleMMNumber"] = GetGridViewString(lblSingleMMNumber);
                    drs[0]["MMNumber"] = GetGridViewString(txtMMNumber);
                }
            }
            return dtTemp;
        }

        private void BindData()
        {
            DataView dv = new DataView(DtMatReturnData);
            dv.RowFilter = "IsDel<>'1'";
            dv.Sort = " MatInStockID,MaterialID ";
            DataTable dtTemp = dv.ToTable();
            if (dtTemp.Rows.Count > 0)
            {
                grdResult.DataSource = dtTemp;
                grdResult.DataBind();
                SetControlAttr(new BsPurchasedetailEntity(), grdResult);
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, CreateDT());
            }
            UIHelper.RunScript(this.UpdatePanel1, "iframeAutoFit();");
        }

        protected void btnAddh_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }

            BsMatreturnEntity entity = new BsMatreturnEntity();
            entity.BillID = GetString(lblBillID);
            entity.BillDate = GetDateTime(cpBillDate);
            entity.ReturnReason = GetString(ddlReturnReason);
            entity.ModifyUserID = CurrentUser.UserID;
            entity.ModifyUserName = CurrentUser.UserName;
            entity.ModifyDate = DateTime.Now;


            BsMatReturnBusiness.SaveOrUpdate(entity, DtMatReturnData, "Update");
            base.LogAction(BaseEnum.ActionType.Modify, entity.BillID, true, null, new EntityBase[] { entity });
            DtMatReturnData = null;
            UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../StockManage/MatReturnList.aspx");
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                string str = e.CommandArgument.ToString();
                int iDel = CommonMethod.ConvertToInt(str);
                AddPro();
                DataTable dt = DtMatReturnData.Copy();

                DataRow[] drs = dt.Select("MatInStockDetailID='" + str + "'  and IsDel<>'1' ");
                if (drs != null && drs.Length > 0)
                {
                    drs[0]["IsDel"] = "1";
                }
                DtMatReturnData = dt.Copy();
                BindData();
                UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
            }
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                #region 删除绑定
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete +

        "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                #endregion
            }
        }
        #endregion

        #region 本地方法
        private bool ValidateData()
        {
            AddPro();
            if (DtMatReturnData.Rows.Count < 1)
            {
                UIHelper.AlertMessage(this.Page, "请添加明细！");
                return false;
            }
            return true;
        }
        #endregion
    }
}
